<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style type="text/css">
        .container{
            margin: 40px auto;
            width: 600px;
            height: 400px;
            border: 1px solid black;
        }
    </style>
</head>
<body>
  <div id="app">
<!--      <p>用户名：<input v-model="username"/></p>-->
<!--      <button @click="conn()">连接</button>-->
<!--      <p>消息：</p>-->
<!--      <textarea v-model="message"></textarea>-->

<!--      <p>目标用户：<input v-model="toUsername"/></p>-->
<!--      <button @click="send()">发送</button>-->
<!--      <hr>-->
      <div class="container">

      </div>
  </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script type="application/javascript">
  var webSocket;
  var app = new Vue({
    el: '#app',
    data: {
        username:'',
        message:'',
        toUsername:''
    },
    methods: {
        conn: function (){
            this.initWebSocket();
        },
        initWebSocket:function (){
            if('WebSocket' in window){
                webSocket = new WebSocket("ws://localhost:8080/webserver/" + this.username);

                // 连接成功后的回调
                webSocket.onopen = e => {
                    console.log("成功连接");
                }

                // 接收服务器的消息
                webSocket.onmessage = e =>{
                   var obj = JSON.parse(e.data);
                   // messageType 1代表上线、2代表下线、3代表在线名单、4代表普通消息

                   if(obj.messageType == 1){
                       console.log(`${obj.username} 用户已上线`);
                   }
                   if(obj.messageType == 2){
                       console.log(`${obj.username} 用户已下线`);
                   }
                   if(obj.messageType == 3){
                       console.log(obj);
                   }
                   if(obj.messageType == 4){
                       console.log(obj);
                   }

                }
                webSocket.onclose = e =>{
                    console.log(e.data);
                }
                webSocket.onerror = e =>{
                    console.log(e.data);
                }
            }
            else {
                console.log("当前浏览器不支持");
            }
        },
        closeWebSocket(){
            webSocket.close();
        },
        send(){
            let message = {
                message: this.message,
                username: this.username,
                to: this.toUsername,
            }
            webSocket.send(JSON.stringify(message));
        }
    }
  })

</script>
</html>